package br.com.study.pool;

import java.math.BigDecimal;
import java.util.List;

public class TestThreadPool {

	private static final int NUMBER_OF_WORKERS = 5;
	private static final int NUMBER_OF_ITERATIONS = 2000000;

	/**
	 * Main entry point.
	 * 
	 * @param args No arguments are used.
	 */
	public static void main(String args[]) {

		double time;
		ThreadPool pool = new ThreadPool(NUMBER_OF_WORKERS);
		time = System.currentTimeMillis();
		for (int i = 0; i < NUMBER_OF_WORKERS; i++) {
			pool.addToPool(new Worker(NUMBER_OF_ITERATIONS));
		}
		pool.complete();
		pool.finalize();
		time = System.currentTimeMillis() - time;

		/*
		 * METRICS PART
		 */
		List<WorkerInfo> metrics = MetricsSingleton.getInstance().getMetrics();

		double sum = 0;
		double min = 100000;
		double max = -1;

		for (WorkerInfo oneWorkerInfo : metrics) {
			// System.out.println(oneWorkerInfo.getThreadName());
			if(null == oneWorkerInfo) {
				System.out.println("TIVEMOS ERROS DE SYNCRONIA");
				break;
			}
			double actualTime = oneWorkerInfo.getTime();
			sum = sum + actualTime;
			if (actualTime > max)
				max = actualTime;
			if (actualTime < min)
				min = actualTime;
		}

		StringBuffer sb = new StringBuffer();
		sb.append(" Number or iterations[" + metrics.size() + "] ");
		sb.append("- min[" + round(min, 2) + "]");
		sb.append("- max[" + round(max, 2) + "]");
		sb.append("- avg[" + round(sum / metrics.size(), 2) + "]");

		System.out.println(sb.toString());
		System.out.println(" The test took " + time + " miliseconds");
	}

	public static double round(double d, int decimalPlace) {
		BigDecimal bd = new BigDecimal(Double.toString(d));
		bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
		return bd.doubleValue();
	}
}
